import React, { Component, Fragment } from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';

import PageHeader from '@/components/PageHeader';
import { FormComponentProps } from '@ant-design/compatible/es/form';

import { BasicProfileDataType } from './data';
import JoinContract from './components/JoinContract';
import BorrowingContract from './components/BorrowingContract';
import SalesContract from './components/SalesContract';

interface DetailProps extends FormComponentProps {
  dispatch: Dispatch<any>;
  location: { query: { id: number; type: number } };
  franchiseeContractDetail: Object;
}

@connect(
  ({
    franchiseeContractDetail,
    loading,
  }: {
    franchiseeContractDetail: BasicProfileDataType;
    loading: {
      effects: { [key: string]: boolean };
    };
  }) => ({
    franchiseeContractDetail,
    loading: loading.effects['franchiseeContractDetail/fetch'],
  }),
)

class Detail extends Component<DetailProps> {
  componentDidMount() {
    const {
      location: { query: { id, type } },
    } = this.props;
    const params = { id, type };
    this.fetchDetailInfo(params);
  }

  componentDidUpdate(prevProps: DetailProps) {
    const {
      location: { query: { id, type } },
    } = this.props;

    if (prevProps.location.query.id !== id) {
      const params = { id, type };
      this.fetchDetailInfo(params);
    }
  }

  fetchDetailInfo = (params: any) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'franchiseeContractDetail/fetch',
      payload: params,
    });
  }

  render() {
    const { franchiseeContractDetail, location: { query: { type } } } = this.props;
    const detailType = Number(type);

    return (
      <Fragment>
        <PageHeader />
        {
          detailType === 1 && <JoinContract detailInfos={franchiseeContractDetail} />
        }
        {
          detailType === 2 && <SalesContract detailInfos={franchiseeContractDetail} />
        }
        {
          detailType === 3 && <BorrowingContract detailInfos={franchiseeContractDetail} />
        }
      </Fragment>
    );
  }
}

export default Detail;
